package steed.util.system;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import steed.util.base.BaseUtil;
import steed.util.system.DataCacheUtil.DataCacheEngine;

/**
 * 单机数据库缓存引擎,不提倡直接用该类,建议通过DataCacheUtil来使用
 * @author 战马
 * 
 * @see DataCacheUtil
 * @see RedisDataCacheEngine
 */
public class StandAloneMachineDataCacheEngine implements DataCacheEngine{
	private Map<String, Object> dataMap = new HashMap<String, Object>();
	private Map<String, Long> timeMap = new HashMap<String, Long>();
	
	public StandAloneMachineDataCacheEngine(){
		init();
	}
	
	private void init(){
		new TaskEngine() {
			@Override
			public void doTask() {
				BaseUtil.getLogger().debug("开始清理缓存数据");
				Map<String, Object> tempDataMap = new HashMap<String, Object>();
				Map<String, Long> tempTimeMap = new HashMap<String, Long>();
				long current = System.currentTimeMillis();
				for(Entry<String, Long> temp:timeMap.entrySet()){
					if (current < temp.getValue()) {
						String key = temp.getKey();
						tempTimeMap.put(key, temp.getValue());
						tempDataMap.put(key, dataMap.get(key));
					}
				}
				dataMap = tempDataMap;
				timeMap = tempTimeMap;
			}
			
			@Override
			protected void startUp(ScheduledExecutorService scheduledExecutorService) {
				scheduledExecutorService.scheduleWithFixedDelay(this, 1, 20, TimeUnit.MINUTES);
			}
			
		}.start();
	}
	@Override
	public <T> T getData(String key,String prefix){
		String key2 = getKey(key, prefix);
		Long time = timeMap.get(key2);
		if (time != null && System.currentTimeMillis() > time) {
			return null;
		}
		return (T) dataMap.get(key2);
	}
	@Override
	public void setData(String key,String prefix,Serializable value){
		setData(key, prefix, value, 1000*60*60*2L);
	}
	@Override
	public void setData(String key,String prefix,Serializable value,Long lifeTime){
		String key2 = getKey(key, prefix);
		dataMap.put(key2, value);
		timeMap.put(key2,System.currentTimeMillis()+lifeTime);
	}

	/**
	 * 该缓存引擎为jvm内存缓存引擎,一旦重启,所有缓存都会消失,
	 * 建议用RedisDataCacheEngine
	 */
	@Deprecated
	@Override
	public void setPermanentData(String key, String prefix, Serializable value) {
		String key2 = getKey(key, prefix);
		dataMap.put(key2, value);
	}

	private String getKey(String key, String prefix) {
		String key2 = key+"_steed_dataCache_"+prefix;
		return key2;
	}

	@Override
	public void removeData(String key, String prefix) {
		timeMap.remove(getKey(key, prefix));
	}
	
}
